package com.example.demo.command;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.table.ArrayTableModel;
import org.springframework.shell.table.BorderStyle;
import org.springframework.shell.table.Table;
import org.springframework.shell.table.TableBuilder;
import org.springframework.shell.table.TableModel;

@ShellComponent
public class HelloCommand {

    @ShellMethod(key = "hello")
    public Table hello() {
        String[][] data = {
            {"PID", "Name", "Status", "CPU%"},
            {"1234", "java", "Running", "2.5%"},
            {"5678", "nginxnginxnginxnginxnginxnginx", "Sleeping", "0.1%"},
            {"9012", "redis", "Running", "1.2%"}
        };


        StringBuilder result = new StringBuilder();
        result.append("Java Processes (Native API):\n");
        result.append("PID\tName\n");
        result.append("----------------\n");

        ProcessHandle.allProcesses()
                .filter(process -> process.info().command()
                        .map(cmd -> cmd.contains("java") || cmd.endsWith(".jar"))
                        .orElse(false))
                .forEach(process -> {
                    process.info();
                    result.append(process.pid()).append("\t")
                            .append(process.info().command().orElse("Unknown")).append("\n");
                });

        System.out.println(result.toString());


        return createTable(data);
    }

    private Table createTable(String[][] data) {
        TableModel model = new ArrayTableModel(data);
        TableBuilder tableBuilder = new TableBuilder(model);

        // 添加边框样式
        tableBuilder.addFullBorder(BorderStyle.fancy_light);

        return tableBuilder.build();
    }



}
